package com.zt.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.zt.reggie.common.BaseContext;
import com.zt.reggie.common.Constant;
import com.zt.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec com.zt.reggie.filter
 * @since 2023 - 02 - 23 - 19:36
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    //这些请求将被放行
    private final String[] uris = {
            "/employee/login", "/employee/logout",
            "/backend/**", "/front/**", "/common/*",
            "/user/login", "/user/sendMsg"  //移动端
    };
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截请求:{}", request.getRequestURI());

        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();

        //2、判断本次请求是否需要处理
        if(check(uris, requestURI)){    //  backend/index.html 将被放行，页面加载会发送其他请求，需要登录
            //3、如果不需要处理，则直接放行
            filterChain.doFilter(request, response);
            return;
        }

        //4-1、员工： 判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute(Constant.SESSION_EMPLOYEE) != null){
            //保存用其他类获取 登录用户id
            Long empId = (Long)request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }

        //4-2、用户： 判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute(Constant.SESSION_USER) != null){
            //保存用其他类获取 登录用户id
            Long userId = (Long)request.getSession().getAttribute(Constant.SESSION_USER);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        //5、如果未登录则返回未登录结果, 通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 检查requestURI 是否匹配上uris 数组中的一个
     * @param uris
     * @param requestURI
     * @return
     */
    private boolean check(String[] uris, String requestURI){
        for(String uri : uris){
            if(pathMatcher.match(uri, requestURI)){
                return true;
            }
        }

        return false;
    }
}
